var mongodb = require('mongodb');//对象
let mongoCt = mongodb.MongoClient;
let ObjectId = mongodb.ObjectId;//_id的包装函数

let sql = 'app';

let open = ({ dbName = sql, collectionName = '', url = 'mongodb://127.0.0.1:27017' }) => new Promise((
  resolve, reject
) => {
  mongoCt.connect(url, { useUnifiedTopology: true }, (err, client) => {
    if(err){
      reject({err,client})
    }else{
      let db = client.db(dbName)
      let collection = db.collection(collectionName)
      resolve({collection,client,ObjectId})
    }
  })
})

//列表
let findList= ({
  collectionName,dbName = sql,
  _limit, _page, _sort, q
}) => {

  // let rule = q ? {title: eval('/'+q+'/') } : {}
  // let rule = q ? {$or:[{title: /q/},{des: /q/},{sub_title: /q/}]} : {}
  let rule = q ? {$or:[{title: new RegExp(q,'g')},{des: eval('/' + q + '/')},{sub_title: eval('/' + q + '/')}]} : {}

  return new Promise((resolve,reject)=>{

    //开库
    open({dbName,collectionName}).then(
      ({collection,client})=>{
        //查询
        collection.find(rule,{
          skip: _page * _limit,
          limit: _limit,
          sort:{[_sort]:1}
        }).toArray((err,result)=>{
          if(!err && result.length > 0){
            resolve({
              err:0,
              data:result
            })
          } else {
            resolve({
              err:1,
              msg:'查无数据'
            })
          }
          client.close()
        })
      }
    ).catch(
      ({client})=>{
        reject({
          err:1,msg:'库链接失败'
        })
        client.close()
      }
    )
  })
};

//详情
let findDetail= ({
  collectionName,dbName=sql,
  _id = null
}) => {
  return new Promise((resolve,reject)=>{
    //开库
    open({dbName,collectionName}).then(
      ({collection,client})=>{
        //查询 详情
        if(_id && _id.length === 24){
          collection.find({_id:ObjectId(_id)},{projection:{_id:0}}).toArray((err,result)=>{
            if(!err && result.length>0){
              resolve({
                err:0,
                msg:'成功',
                data:result[0]
              })
            }else{
              resolve({
                err:1,
                msg:'查无数据'
              })
            }
            client.close()
          })
        }else{
          resolve({
            err:1,
            msg:'_id有误，且为必传参数'
          });
          client.close()
        }
      }
    ).catch(
      ({client})=>{
        reject({
          err:1,msg:'库链接失败'
        })
        client.close()
      }
    )

  })
};

exports.open = open
exports.findList = findList
exports.findDetail=findDetail
